package de.wepner.texteditor.command;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;

import javax.swing.JFileChooser;

import de.wepner.texteditor.io.IOUtils;
import de.wepner.texteditor.model.EditedFile;
import de.wepner.texteditor.model.EditorData;


/**
 * <p>Opens a file chooser, so the user can choose a file, and loads
 * the selected file.</p>
 * 
 * @author Richard Wepner
 */
public class LoadFileCommand extends Command {
    
    private final EditorData data;
    private final Component window;
    
    public LoadFileCommand(EditorData data, Component window) {
        this.data = data;
        this.window = window;
    }
    
    
    @Override
    public void actionPerformed(ActionEvent e) {
        File folder = null;
        if (this.data.getEditedFile() != null && this.data.getEditedFile().getFile() != null) {
            folder = this.data.getEditedFile().getFile().getParentFile();
        }
        JFileChooser chooser = new JFileChooser(folder);
        if (chooser.showOpenDialog(this.window) == JFileChooser.APPROVE_OPTION) {
            File selected = chooser.getSelectedFile();
            if (selected.exists() && selected.isFile() && selected.canRead()) {
                EditedFile file = new EditedFile(selected, IOUtils.loadFile(selected));
                this.data.setEditedFile(file);
            }
        }
    }
}
